<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header flexAic">
          <span>提现管理</span>
          <el-tooltip class="box-item" effect="dark" placement="bottom">
            <template #content>
              可提现余额=代收钱包的收入金额-代收钱包的已提现金额（提现中或退款中
              <br />
              的订单金额无法被提现，自营收入的订单金额无法被提现）
            </template>
            <img
              style="width: 20px; margin-left: 10px"
              src="https://b.gaokaow.cc/question@2x.png"
              alt=""
            />
          </el-tooltip>
          <span class="titleMon"
            >可提现余额
            <span class="moneyNum">{{ moneyNum ? moneyNum : '0.00' }}</span> 元
          </span>
        </div>
      </template>
      <div class="grey">
        尊敬的用户您好，提现每月限1次，每月20号之前申请提现，会在当月25号（工作日）左右汇款，20号之后申请提现，会顺延到下个月25号汇款！
      </div>
      <div class="account_box">
        <div class="left">提现申请</div>
        <div class="right">支付成功后，刷新页面可查看余额状态</div>
      </div>

      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
        :hide-required-asterisk="true"
        style="margin-bottom: 10px"
      >
        <el-form-item label="提现金额" prop="amout">
          <el-input style="width: 280px" v-model="ruleForm.amout" />
          <span class="txt" style="display: inline-block; margin-left: 10px"
            >元</span
          >
        </el-form-item>
        <el-form-item
          label="提现账户"
          prop="info"
          class="hide-required-asterisk"
        >
          <el-table
            :data="tableData"
            style="width: 100%; height: 120px"
            ref="refTable"
            v-model="ruleForm.info"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" />
            <el-table-column prop="name" label="企业名称/个人姓名" />
            <el-table-column prop="bankRoot" label="银行账户" />
            <el-table-column prop="bankAddress" label="开户行" />
            <el-table-column label="操作" width="180">
              <template #default="scope">
                <span class="edit" @click="handleEdit(scope.row)"> 编辑 </span>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item style="margin-left: 10px; color: rgb(153, 153, 153)">
          <span class="info">如有疑问请联系您的专属客服</span>
        </el-form-item>
        <el-form-item style="margin-left: 80px">
          <el-button
            type="primary"
            class="primary"
            :disabled="moneyNum <= 0 ? true : false"
            @click="submitForm(ruleFormRef)"
          >
            提交申请
          </el-button>
        </el-form-item>
      </el-form>

      <div class="tableTitle">
        <div>提现记录</div>
        <div>
          <el-date-picker
            @change="saveChangeTime"
            v-model="ruleForm.time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :popper-options="{ placement: 'top-end' }"
          />
        </div>
      </div>
      <el-table
        :data="dataList"
        v-loading="loading"
        style="width: 100%"
        :default-sort="{ prop: 'price', order: 'descending' }"
      >
        <el-table-column prop="mobile" label="申请人" width="180" />
        <el-table-column prop="create_time" label="申请时间" width="180" />
        <el-table-column label="提现账号" width="180">
          <template #default="">
            <p>
              {{ UserInfo.name + UserInfo.bankRoot + UserInfo.bankName }}
            </p>
          </template>
        </el-table-column>
        <el-table-column prop="fee" label="提现金额" sortable>
          <template #header="scope">
            <span style="display: flex; align-items: center">
              {{ scope.column.label }}

              <SortDown
                :class="currentStyle == 1 ? 'active' : ''"
                @click="sortBtn(1)"
                style="height: 1em"
              />
              <SortUp
                :class="currentStyle == 2 ? 'active' : ''"
                @click="sortBtn(2)"
                style="height: 1em; margin-left: -7px"
              />
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="status" label="状态" /> -->
        <el-table-column label="状态" width="180">
          <template #default="scope">
            {{
              scope.row.status === 0
                ? '待审'
                : scope.row.status === 1
                  ? '已处理'
                  : scope.row.status === 2
                    ? '驳回'
                    : '未知状态'
            }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="remark" label="备注" /> -->
        <el-table-column label="备注" prop="remark">
          <template #default="scope">
            <p>{{ scope.row.remark ?? '-' }}</p>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      v-model="dialogVisible"
      title="编辑机构银行账户信息"
      width="527px"
      custom-class="titleStyle"
    >
      <p class="infoContract">
        <WarningFilled
          style="width: 1.5em; height: 1.5em; margin-right: 8px"
        />账户信息必须与签约时提交的合同主体一致
      </p>
      <el-form ref="formRef" :rules="rules" :model="form" label-width="140px">
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio
              :value="item.type"
              size="large"
              v-for="item in typeList"
              >{{ item.name }}</el-radio
            >
            <!-- <el-radio value="2" size="large">个人账号</el-radio> -->
          </el-radio-group>
        </el-form-item>
        <el-form-item label="企业名称/个人姓名" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入"
            class="styleInput"
          />
        </el-form-item>
        <el-form-item label="银行账号" prop="bankRoot">
          <el-input
            v-model="form.bankRoot"
            placeholder="请输入"
            @input="handleInput(form.bankRoot)"
            class="styleInput"
          />
        </el-form-item>
        <el-form-item label="开户行" prop="bankName">
          <el-input
            v-model="form.bankAddress"
            placeholder="请输入"
            class="styleInput"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button class="footerBtn" @click="saveHandle(form)">
          提交保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import withdraw from '@/modules';
const {
  bankListAPI,
  cashListPAI,
  commitCashAPI,
  updateBankApi,
  accountBalanceApi,
} = withdraw;
const ruleFormRef = ref();
const formRef = ref();
const moneyNum = ref('');
const dialogVisible = ref(false);
const refTable = ref(null);
const currentStyle = ref(null);
const UserInfo = ref('');
import { ElMessage } from 'element-plus';
import { formatDateYMD } from '@/utils';
const loading = ref(false);
const typeList = ref([
  {
    type: 1,
    name: '公司账户',
  },
  {
    type: 2,
    name: '个人账户',
  },
]);
const form = ref({
  name: '',
  bankRoot: '',
  bankName: '',
  type: '1',
});
const tableConfig = ref({
  page: 1,
  pageSize: 10,
  type: 1,
  startTime: '',
  endTime: '',
});

const ruleForm = reactive({
  amout: '',
  info: '',
  time: '',
});
const dataList = ref([]);
const tableData = ref([]);
const sortBtn = (type) => {
  currentStyle.value = type;
};
const saveChangeTime = (val) => {
  loading.value = true;
  if (val) {
    tableConfig.value.startTime = formatDateYMD(new Date(val[0]));
    tableConfig.value.endTime = formatDateYMD(new Date(val[1]));
  } else {
    tableConfig.value.starTime = '';
    tableConfig.value.endTime = '';
  }
  WithdrawalTableDataList();
};

const rules = reactive({
  amout: [{ required: true, message: '金额不能为空', trigger: 'blur' }],
  info: [{ required: true, message: '', trigger: 'blur' }],
  name: [
    { required: true, message: '请输入企业名称/个人姓名', trigger: 'blur' },
  ],
  bankRoot: [{ required: true, message: '请输入银行账号', trigger: 'blur' }],
  bankName: [{ required: true, message: '请输入开户行', trigger: 'blur' }],
  type: [{ required: true, message: '', trigger: 'blur' }],
});
const saveEditBankApi = (params) => {
  updateBankApi(params).then(async (res) => {
    if (res.code == 20000) {
      await getTableData();
    }
    ElMessage({
      message: res.msg,
      type: 'success',
    });
  });
};
const handleEdit = (row) => {
  Object.assign(form.value, row);
  dialogVisible.value = true;
};
//选中当前行数据
const handleSelectionChange = (val) => {
  ruleForm.info = val[0];
};
// 提交申请api
const getcommitCashAPI = (res) => {
  commitCashAPI(res).then(({ data }) => {
    ElMessage({
      message: data.msg,
      type: 'error',
    });
  });
};
// 只允许输入数字
const handleInput = (data) => {
  form.value.bankRoot = data.replace(/[^\d]/g, '');
};

const saveHandle = async () => {
  // 提交表单前先进行验证
  try {
    await formRef.value.validate(); // 触发验证
    // 如果验证通过，这里可以执行提交操作

    await saveEditBankApi(form.value);

    // 在这里添加你的提交逻辑，比如 API 请求
    dialogVisible.value = false; // 提交后关闭对话框
  } catch (error) {
    console.log('error:', error);
  }
};

const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      getcommitCashAPI(ruleForm);
      ruleForm.amout = '';
      ruleForm.info = null;
      refTable.value.clearSelection();
    } else {
    }
  });
};

//提现银行列表
const getTableData = () => {
  const { page, pageSize, type } = tableConfig.value;
  bankListAPI({ page, pageSize, type }).then(({ data }) => {
    tableData.value = data.data;
    loading.value = false;
  });
};
//提现记录
const WithdrawalTableDataList = () => {
  delete tableConfig.value.time;
  cashListPAI(tableConfig.value).then(({ data }) => {
    dataList.value = data.data;
    loading.value = false;
    dataList.value.map((item) => {
      if (item.info) return (UserInfo.value = JSON.parse(item.info));
    });
  });
};
//账户余额
const getUserMoney = async () => {
  try {
    const { data } = await accountBalanceApi();
    moneyNum.value = data.balance;
  } catch (error) {
    console.log('error:', error);
  }
};
onMounted(() => {
  getTableData();
  WithdrawalTableDataList();
  getUserMoney();
});
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.module.scss';
@import '@/assets/styles/global.scss';
:deep(.caret-wrapper) {
  display: none !important;
}
:deep(.el-form-item__label) {
  font-weight: 400;
  color: #86909c;
  font-size: 14px;
}
:deep(.el-dialog__footer) {
  display: flex;
  justify-content: right;
  align-items: center;
  padding-top: 15px;
}
:deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: var(--primary-color);
  border-color: var(--primary-color);
}
:deep(.el-radio__input.is-checked + .el-radio__label) {
  color: var(--primary-color);
}
:deep(.el-dialog__body) {
  padding: 24px 24px 16px 24px !important;
  margin-top: 0;
}
:deep(.el-dialog__header) {
  height: 45px;
  min-height: 0;
}
:deep(.el-button--primary) {
  background-color: var(--primary-color);
  border-color: var(--primary-color);
}
:deep(.el-button.is-disabled) {
  opacity: 0.5;
  background-color: var(--primary-color);
}
:deep(.el-button.is-disabled:hover) {
  opacity: 0.5;
  background-color: var(--primary-color);
  border-color: var(--primary-color);
}
// :deep(.el-button) {
//   color: #fff;
//   background-color: #165dff !important;
//   border-color: #165dff !important;
// }
.infoContract {
  display: flex;
  align-items: center;
  height: 40px;
  width: 420px;
  background-color: rgb(254, 245, 236);
  margin-bottom: 20px;
  text-align: left;
  padding-left: 20px;
  color: rgb(233, 180, 125);
  line-height: 40px;
  border-radius: 4px;
}
.hide-required-asterisk .el-form-item__label::after {
  content: ''; /* 清空内容 */
  display: none; /* 隐藏 */
}
.grey {
  margin: 20px 0 25px 0;
}
.account_box {
  display: flex;
  margin-bottom: 20px;
  .left {
    font-weight: 600;
    color: #1d2129;
    line-height: 16px;
    margin-right: 10px;
  }
  .right {
    font-weight: 400;
    color: #86909c;
    line-height: 14px;
    font-size: 14px;
  }
}
.info {
  margin-left: 70px;
  display: inline-block;
}
.footerBtn {
  background-color: var(--primary-color);
  border-color: var(--primary-color);
  color: #fff;
}
.primary {
  font-size: 14px;
  font-weight: 400;
  width: 170px;
  height: 40px;
  line-height: 40px;
  color: #fff;
}
.edit {
  color: var(--primary-color);
  cursor: pointer;
}
.primary:hover {
  opacity: 0.9;
}
.styleInput {
  width: 280px;
  height: 40px;
}

.cards {
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex-wrap: wrap;
  margin-top: 20px;
}
.card-header {
  display: flex;
  align-items: center;
}
.tableTitle {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}
.active {
  color: var(--primary-color);
}
.moneyNum {
  font-size: 14px;
  font-weight: 600;
  color: #1d2129;
}
.titleMon {
  color: #86909c;
  font-size: 14px;
  font-weight: 400;
  display: inline-block;
  margin-left: 5px;
}
</style>
